package com.zw.re.service;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.connection.RedisConnection;
import org.springframework.data.redis.core.RedisCallback;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.RedisSerializer;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Map;
import java.util.Set;

/**
 * Created by zwz
 * date 2016/11/29
 * project com.zw.re.service
 */
@Service
public class HashMapOpt {

    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private SerializerUtil serializerUtil;

    @Resource(name = "jackson2JsonRedisSerializer")
    private RedisSerializer jackson2JsonRedisSerializer;

    /**
     *  put一个Hash Map 到redis
     *  <p> 当以这种方式存储数据时候，再读取出来的数据会是JSON 字符串 不再是存入时的object</p>
     * @param   key Object
     * @param   object  HashMap
     */
    
    public void insertAll(Object key, Map object) {
        redisTemplate.setHashValueSerializer(jackson2JsonRedisSerializer);
        redisTemplate.opsForHash().putAll(key, object);
    }

    /**
     * put 一组键值对
     *
     * @param key   Object
     * @param hashKey   Object
     * @param value Object
     */
    
    public void insert(Object key, Object hashKey, Object value) {
        redisTemplate.setHashValueSerializer(jackson2JsonRedisSerializer);
        redisTemplate.opsForHash().put(key, hashKey,value);
    }

    /**
     * 查询指定key的数据
     *
     * @param key Object
     * @return
     */
    
    public Map queryAll(Object key) {
        redisTemplate.setHashValueSerializer(redisTemplate.getStringSerializer());
        return redisTemplate.opsForHash().entries(key);
    }

    /**
     * 根据Map 的键查询value
     * @param key   Object
     * @param hashKey   Object
     * @return
     */
    
    public Object queryByHk(Object key, Object hashKey) {
        redisTemplate.setHashValueSerializer(redisTemplate.getStringSerializer());
        return redisTemplate.opsForHash().get(key, hashKey);
    }

    public Long size(Object key){
        return redisTemplate.opsForHash().size(key);
    }

    /**
     * 根据Map的Key 删  value
     * @param key Object
     * @param hashKey Object...
     */
    public Long deleteBykey(Object key, Object hashKey){
        return redisTemplate.opsForHash().delete(key, hashKey);
    }

    /**
     * 删除一组键值
     * @param key
     * @param hashKeys
     * @return
     */
    public Long deleteBykeys(Object key, Set hashKeys){
        final byte[] rawKey = serializerUtil.serializerKey(key);
        final byte[][] rawHashKeys = serializerUtil.serializerValue(hashKeys);

        return (Long)redisTemplate.execute(new RedisCallback<Long>() {

            public Long doInRedis(RedisConnection connection) {
                return connection.hDel(rawKey, rawHashKeys);
            }
        }, true);
    }

}
